package com.huangmb.anymark.app.fragment;

import android.content.Intent;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.*;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.Projection;
import com.amap.api.maps.model.*;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import com.huangmb.androidlib.utils.Logger;
import com.huangmb.anymark.app.R;
import com.huangmb.anymark.app.activity.AddMarkerActivity;
import com.huangmb.anymark.app.activity.UserCenterActivity;
import com.huangmb.anymark.app.adapter.MarkerListAdapter;
import com.huangmb.anymark.app.api.BaseApi;
import com.huangmb.anymark.app.api.UserMarkerApi;
import com.huangmb.anymark.app.app.AppConstants;
import com.huangmb.anymark.app.model.UserMarker;
import com.huangmb.anymark.app.utils.Locator;
import com.malinskiy.superrecyclerview.OnMoreListener;
import com.malinskiy.superrecyclerview.SuperRecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * A placeholder fragment containing a simple view.
 */
public class MainActivityFragment extends BaseMapFragment {
    private final static String TAG = MainActivityFragment.class.getSimpleName();
    private FloatingActionsMenu mFloatingMenu;
    private View mShadowView;
    private SuperRecyclerView recyclerView;
    private MarkerListAdapter markerListAdapter;



    private Circle mCircle;
    private double mCircleRadius = 1000;
    private Marker mMyLocationMarker;
    private ArrayList<Marker> mMarkerList;
    private ProgressBar mProgressBar;


    private boolean isNeedReload = false;

    public MainActivityFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_main, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mProgressBar = getProgressbar();
        recyclerView = (SuperRecyclerView) view.findViewById(R.id.container);
        MapView mapView = (MapView) view.findViewById(R.id.map);
        setUpMapView(mapView, savedInstanceState);
        mFloatingMenu = (FloatingActionsMenu) view.findViewById(R.id.floating_menu);
        mShadowView = view.findViewById(R.id.shade_cover);
        initFloatingMenu();
        markerListAdapter = new MarkerListAdapter(getContext());
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(markerListAdapter);

        recyclerView.setupMoreListener(new OnMoreListener() {
            @Override
            public void onMoreAsked(int overallItemsCount, int itemsBeforeMore, int maxLastVisiblePosition) {
                toast("加载更多" + overallItemsCount + " " + itemsBeforeMore + " " + maxLastVisiblePosition);
            }
        }, 0);

        //添加滚动监听，实现底部滚动栏滚动后地图上对应的标记做出响应，这里是弹出信息窗口
        //recyclerView.addOnScrollListener(new AutoSelectMarkerListener());
        //((LinearLayoutManager) recyclerView.getLayoutManager()).setSmoothScrollbarEnabled(true);

        setHasOptionsMenu(true);
        mProgressBar.setVisibility(View.VISIBLE);
        toast("正在定位");
        Locator.startLocationOnce(new Locator.LocationListener() {
            @Override
            public void onLocationChanged(@NonNull AMapLocation aMapLocation) {
                mProgressBar.setVisibility(View.GONE);
                toast("定位完成");
                LatLng latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                getAMap().moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14));
                findNearBy(latLng, null);
            }

            @Override
            public void onFail(AMapLocation aMapLocation) {
                mProgressBar.setVisibility(View.GONE);
                toast("定位失败");
            }
        });
    }

    private void initFloatingMenu() {

        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btn_add_live:
                        AddMarkerActivity.newInstance(getContext(), AppConstants.TYPE_ADD_LIVE);
                        break;
                    case R.id.btn_add_place:
                        AddMarkerActivity.newInstance(getContext(), AppConstants.TYPE_ADD_PLACE);
                        break;
                    case R.id.btn_add_schedule:
                        AddMarkerActivity.newInstance(getContext(), AppConstants.TYPE_ADD_SCHEDULE);
                        break;
                }
                mFloatingMenu.collapse();

            }
        };
        mFloatingMenu.findViewById(R.id.btn_add_live).setOnClickListener(listener);
        mFloatingMenu.findViewById(R.id.btn_add_place).setOnClickListener(listener);
        mFloatingMenu.findViewById(R.id.btn_add_schedule).setOnClickListener(listener);
        mShadowView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mFloatingMenu.collapse();
            }
        });
        mFloatingMenu.setOnFloatingActionsMenuUpdateListener(new FloatingActionsMenu.OnFloatingActionsMenuUpdateListener() {
            @Override
            public void onMenuExpanded() {
                mShadowView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onMenuCollapsed() {
                mShadowView.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        savePositionToPreference(mAMap.getCameraPosition().target);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_main, menu);
        MenuItem item = menu.findItem(R.id.action_search);
        //item.collapseActionView();
        MenuItemCompat.setOnActionExpandListener(item, new MenuItemCompat.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                return true;
            }

            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                //toast("关闭");
                if (isNeedReload) {
                    Logger.d(TAG, "重新加载数据");
                    findNearBy();
                }
                isNeedReload = false;
                return true;
            }
        });
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);//SearchView) item.getActionView();
        //searchView.setIconified(false);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                //toast("搜索：" + query);
                isNeedReload = true;
                findNearBy(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                Logger.d(TAG, newText);
                return false;
            }
        });
        ImageView submitBtn = (ImageView) searchView.findViewById(android.support.v7.appcompat.R.id.search_go_btn);
        if (submitBtn != null) {
            submitBtn.setImageResource(R.drawable.ic_search);
        }
        searchView.setSubmitButtonEnabled(true);
        //搜索框关闭
       /* searchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                toast("关闭");
                findNearBy();
                return false;
            }
        });*/

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        /*if (id == R.id.action_search) {
            toast("搜索");
            //TODO 这里假定这个是触发重新搜寻的按钮
            findNearBy();
            return true;
        }*/
        if (id == R.id.action_me) {
            //toast("个人中心");
            Intent intent = new Intent(getActivity(), UserCenterActivity.class);
            startActivity(intent);
            return true;
        }
        if (id == R.id.action_settings) {
            toast(R.string.action_settings);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
        super.onInfoWindowClick(marker);
        if (marker.equals(mMyLocationMarker)) {
            toast(R.string.searching);
            findNearBy();
        }
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        if (marker.equals(mMyLocationMarker)) {
            // toast("点击了中心点");
            if (marker.isInfoWindowShown()) {
                marker.hideInfoWindow();
            } else {
                marker.showInfoWindow();
            }
            return true;
        }
        /*if (marker.isInfoWindowShown()) {
            marker.hideInfoWindow();
        } else {
            marker.showInfoWindow();
        }*/
        int index = mMarkerList.indexOf(marker);
        if (index != -1) {
            Logger.d(TAG, "点击了 " + marker.getTitle() + " " + index);
            //实现点击标记点，底部滚动栏自动定位到对应的条目
            ((LinearLayoutManager) recyclerView.getRecyclerView().getLayoutManager()).scrollToPositionWithOffset(index, 0);
        }
        return super.onMarkerClick(marker);
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        super.onCameraChange(cameraPosition);
        refreshCirclePosition();
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        super.onCameraChangeFinish(cameraPosition);
        if (!isNeedIgnoreCameraChange()) {

            refreshMarker();
            if (mMyLocationMarker != null) {
                mMyLocationMarker.showInfoWindow();
            }
        }

    }

    private void refreshCirclePosition() {
        refreshCirclePosition(mAMap.getCameraPosition().target);
    }

    private void refreshCirclePosition(LatLng pos) {
        //计算圆圈的半径
        Projection projection = getAMap().getProjection();
        Point center = projection.toScreenLocation(pos);
        LatLng p1 = projection.fromScreenLocation(new Point(30, center.y));

        mCircleRadius = AMapUtils.calculateLineDistance(p1, pos);
        if (mCircleRadius > 5000) {
            mCircleRadius = 5000;
        }
        if (mCircle == null) {
            mCircle = mAMap.addCircle(new CircleOptions()
                    .center(pos)
                    .radius(mCircleRadius)
                    .strokeColor(Color.BLUE)
                    //.fillColor(Color.WHITE)
                    .strokeWidth(3)
            );
        } else {
            mCircle.setCenter(pos);
            mCircle.setRadius(mCircleRadius);
        }

        if (mMyLocationMarker == null) {
            MarkerOptions options = new MarkerOptions();
            options.position(pos);
            options.zIndex(10);
            options.title("刷新");
            options.icon(BitmapDescriptorFactory.fromResource(android.R.drawable.ic_menu_myplaces));
            mMyLocationMarker = mAMap.addMarker(options);

        } else {
            mMyLocationMarker.setPosition(pos);
        }


    }

    private void showMarkers(List<UserMarker> list) {
        if (list == null) {
            return;
        }
        ArrayList<MarkerOptions> optionsList = new ArrayList<>();

        int i = 0;
        //TODO 设置图标
        for (UserMarker item : list) {
            i++;
            MarkerOptions options = new MarkerOptions();
            LatLng pos = new LatLng(item.getLatitude(), item.getLongitude());
            options.position(pos);
            options.title(item.getTitle());
            TextView posText = (TextView) getActivity().getLayoutInflater().inflate(R.layout.marker, null);
            posText.setText("" + i);
            options.icon(BitmapDescriptorFactory.fromView(posText));

            optionsList.add(options);

        }
        Logger.d(TAG, "绘制标记数目" + optionsList.size());
        clearMarkers();
        mMarkerList = mAMap.addMarkers(optionsList, false);
        refreshCirclePosition();
    }

    private Bitmap getTintBitmap(Bitmap bitmap, int color) {
        Bitmap output = Bitmap
                .createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Paint p = new Paint();
        p.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN));
        new Canvas(output).drawBitmap(bitmap, 0, 0, p);
        return output;
    }

    public void refreshMarker() {
        Logger.d(TAG, "refreshMarker");
        if (mMarkerList != null && !mMarkerList.isEmpty()) {
            for (Marker marker : mMarkerList) {
                if (mCircle.contains(marker.getPosition())) {
                    marker.setVisible(true);
                } else {
                    marker.setVisible(false);
                }
            }
        }
    }

    private void clearMarkers() {
        mAMap.clear();
        mCircle = null;
        mMyLocationMarker = null;
        if (mMarkerList != null) {
            mMarkerList.clear();
        }

    }

    private void findNearBy() {
        LatLng pos = getAMap().getCameraPosition().target;
        findNearBy(pos, null);
    }

    private void findNearBy(String key) {
        //获取地图的中心位置作为查询周边标注的基准点
        LatLng pos = getAMap().getCameraPosition().target;
        findNearBy(pos, key);
    }

    private void findNearBy(LatLng pos, String key) {

        //调用封装的API向服务器请求查找该地点周边的标注
        mProgressBar.setVisibility(View.VISIBLE);
        UserMarkerApi.nearby(pos, (int) mCircleRadius, key, null, true, new BaseApi.AbsListener(mProgressBar) {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                //请求成功的回调
                List<UserMarker> list = JSON.parseArray(result, UserMarker.class);
                Logger.d(TAG, "搜索成功，返回结果" + list.size());
                markerListAdapter.setData(list);//将请求结果在列表中展示
                showMarkers(list);//将请求结果在地图上展示
                if (list.isEmpty()) {
                    toast("周边无数据");
                }
            }
        });
    }


    private class AutoSelectMarkerListener extends RecyclerView.OnScrollListener {
        //当RecyclerView已滚动至第一个或最后一个时，继续拖动只会触发onScrollStateChanged，
        // 导致多次重复更新地图上的marker，造成屏幕闪动
        boolean hasChanged = false;//该标志用于判断经过了滚动，过滤掉上述拖动情况
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getRecyclerView().getLayoutManager();

        int last;

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            //Logger.d(TAG, "onScrollStateChanged " + newState);
            if (!hasChanged || newState != RecyclerView.SCROLL_STATE_IDLE) {
                return;
            }
            hasChanged = false;
           /* if (mMarkerList != null) {
                int position = layoutManager.findFirstVisibleItemPosition();
                if (position < mMarkerList.size()) {

                    if(last == position){
                        return;
                    }
                    if(last != -1){
                        Marker marker = mMarkerList.get(last);
                        UserMarker data = markerListAdapter.getData().get(position);
                        Bitmap big = getTintBitmap(mIconNormal,MarkerUtils.getMappingColor(data));
                        marker.setIcon(BitmapDescriptorFactory.fromBitmap(big));

                    }
                    Marker marker = mMarkerList.get(position);
                    //marker.setObject(marker.getIcons());
                    UserMarker data = markerListAdapter.getData().get(position);
                    Bitmap big = getTintBitmap(mIconBig,MarkerUtils.getMappingColor(data));
                    marker.setIcon(BitmapDescriptorFactory.fromBitmap(big));
                    //Logger.d(TAG,"onScrollStateChanged 弹出信息窗口");
                    //marker.showInfoWindow();
                    last = position;
                }
            }*/

        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            //Logger.d(TAG, "onScrolled");
            hasChanged = true;
        }
    }
}
